import { itemRecheckService } from '@/services/salaryManage/salaryCalculate';
import { isSuccess } from '@/utils/request';
import { message } from 'antd';
import modelType from '../../constant/modelTypeConstant';

function* getState(select, namespace) {
    return yield select(state => state[namespace]);
}

function* searchPostData(select, namespace) {
    const currentState = yield* getState(select, namespace);

    const searchCondition = {
        searchModel: currentState.searchModel,
        pagination: currentState.pagination || {
            current: 1,
            pageSize: 10
        },
        rootSalaryItemId: currentState.rootSalaryItemId
    };

    const { searchModel, pagination, rootSalaryItemId } = searchCondition;
    const periodStr = currentState.period || '';
    const year = periodStr.substr(0, 4);
    const month = periodStr.substr(5);

    return {
        year,
        month: month ? String(parseInt(month, 10)) : month,
        page: {
            pageNo: pagination.current,
            pageSize: pagination.pageSize
        },
        dynamicQueryName: currentState.dynamicQueryName,
        searchModel,
        rootSalaryItemId
    };
}

const namespace = 'itemRecheckModel';
const itemRecheckModel = {
    namespace,
    state: {
        // 当前薪资细项id
        rootSalaryItemId: null,
        period: null,
        searchModel: {},

        tableLoading: false,
        rowKey: 'id',
        pagination: {
            current: 1,
            pageSize: 10
        },
        tableHeader: [],
        dynamicQueryName: '',
        dynamicQueryConditionsMapList: [],
        dataSource: [],

        currentRecord: null,
        renderedTableRows: [],
        hoverRowData: []
    },
    reducers: {
        [modelType.SET_MULTI_STORE](state, action) {
            return {
                ...state,
                ...action.payload
            };
        },

        [modelType.SET_LOADING](state, action) {
            return {
                ...state,
                ...action.payload
            };
        },
        /**
         * 更变月份
         * @param action.payload 月份
         */
        [modelType.SET_PERIOD](state, action) {
            const { payload: period } = action;

            return { ...state, period };
        },

        [modelType.SET_SEARCH_CONDITION](state, action) {
            const { searchModel } = state;
            return {
                ...state,
                searchModel: {
                    ...searchModel,
                    ...action.payload
                }
            };
        },

        [modelType.SET_PAGE_INFO](state, action) {
            const { pageSize, total, pageNo: current, rows: dataSource } = action.payload.data;

            const pagination = {
                ...state.pagination,
                pageSize: pageSize || 10,
                current: current || 1,
                total
            };

            return {
                ...state,
                dataSource,
                pagination
            };
        },

        [modelType.SET_TABLE_HEADER](state, action) {
            return {
                ...state,
                tableHeader: action.payload
            };
        },
        [modelType.SET_PAGINATION](state, action) {
            const pagination = {
                ...state.pagination,
                current: action.payload.current || state.pagination.current,
                pageSize: action.payload.pageSize || state.pagination.pageSize
            };

            return {
                ...state,
                pagination
            };
        }
    },
    effects: {
        *[modelType.E_INIT](state, { put, call, select, all }) {
            if (state?.payload?.rootSalaryItemId) {
                yield put({
                    type: modelType.SET_MULTI_STORE,
                    payload: { rootSalaryItemId: state.payload.rootSalaryItemId }
                });
            }

            yield put({
                type: modelType.SET_SEARCH_CONDITION,
                payload: state.payload
            });

            if (state?.payload?.period) {
                // 设置默认月份
                yield put({
                    type: modelType.SET_PERIOD,
                    payload: state.payload.period
                });
            } else {
                const response = yield call(itemRecheckService.latestSalaryYearMonth);

                if (!isSuccess(response)) {
                    return;
                }
                const { year, month } = response.data;
                // 设置默认月份
                yield put({
                    type: modelType.SET_PERIOD,
                    payload: `${year}-${(month < 10 ? '0' : '') + month}`
                });
            }

            const postData = yield* searchPostData(select, namespace);

            yield put({
                type: modelType.SET_LOADING,
                payload: { tableLoading: true }
            });
            const [headerResponse, recordResponse] = yield all([
                // 查询表头数据
                call(itemRecheckService.queryTableHeadData, {
                    year: postData.year,
                    month: postData.month,
                    parentId: postData.rootSalaryItemId,
                    leafSalaryItemId: postData.searchModel?.leafSalaryItemId,
                    organizationCode: postData.searchModel?.organizationCode
                }),
                // 查询表格表体数据
                call(itemRecheckService.queryTableBodyData, postData)
            ]);
            yield put({
                type: modelType.SET_LOADING,
                payload: { tableLoading: false }
            });
            if (isSuccess(headerResponse)) {
                const { tableHeaderItemList, dynamicQueryName, dynamicQueryConditionsMapList } = headerResponse.data;
                yield put({
                    type: modelType.SET_MULTI_STORE,
                    payload: {
                        tableHeader: tableHeaderItemList,
                        dynamicQueryName: dynamicQueryName || postData.dynamicQueryName,
                        dynamicQueryConditionsMapList
                    }
                });
            } else {
                message.error(`请求表头数据失败：${headerResponse.msg}`);
            }

            if (isSuccess(recordResponse)) {
                yield put({
                    type: modelType.SET_PAGE_INFO,
                    payload: recordResponse
                });
            } else {
                message.error(`请求表身数据失败：${recordResponse.msg}`);
            }
        },

        //  搜索
        *[modelType.E_SEARCH](s, { put, call, select, all }) {
            // 设置查询条件
            if (s.payload) {
                yield put({
                    type: modelType.SET_SEARCH_CONDITION,
                    payload: s.payload
                });
            }

            const postData = yield* searchPostData(select, namespace);

            yield put({
                type: modelType.SET_LOADING,
                payload: { tableLoading: true }
            });

            const [headerResponse, response] = yield all([
                // 查询表头数据
                call(itemRecheckService.queryTableHeadData, {
                    year: postData.year,
                    month: postData.month,
                    parentId: postData.rootSalaryItemId,
                    leafSalaryItemId: postData.searchModel?.leafSalaryItemId,
                    organizationCode: postData.searchModel?.organizationCode
                }),
                call(itemRecheckService.queryTableBodyData, postData)
            ]);
            if (isSuccess(headerResponse)) {
                const { tableHeaderItemList, dynamicQueryName, dynamicQueryConditionsMapList } = headerResponse.data;
                yield put({
                    type: modelType.SET_MULTI_STORE,
                    payload: {
                        tableHeader: tableHeaderItemList,
                        dynamicQueryName: dynamicQueryName || postData.dynamicQueryName,
                        dynamicQueryConditionsMapList
                    }
                });
            } else {
                message.error(`请求表头数据失败：${headerResponse.msg}`);
            }
            if (isSuccess(response)) {
                yield put({
                    type: modelType.SET_PAGE_INFO,
                    payload: response
                });
            } else {
                message.error(`请求表身数据失败：${response.msg}`);
            }

            yield put({
                type: modelType.SET_LOADING,
                payload: { tableLoading: false }
            });
        },
        *[modelType.E_TABLE_PAGE_CHANGE](state, { put }) {
            yield put({
                type: modelType.SET_PAGINATION,
                payload: state.payload
            });
            yield put({ type: modelType.E_SEARCH });
        }
    }
};

export default itemRecheckModel;
